import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    Connection connection=null;
    PreparedStatement preparedStatement=null;

    //用户登录时
    //隐含约束（用户名需要唯一）
    public User selectByName(String username) throws SQLException {
        ResultSet resultSet=null;
        try {
            connection=DBUtil.getConnection();

            String sql="select * from user where username=?";
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            //发送
            resultSet=preparedStatement.executeQuery();
            //遍历结果集合 （一条数据，怎么得到各个属性?）
            if(resultSet.next()){
                User user=new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,preparedStatement,resultSet);
        }
        return null;
    }


    //根据用户id来查询用户详情---获取用户信息时需要用到（删除博客时）
    public User selectById(int userId) throws SQLException {
        ResultSet resultSet=null;
        try {
            connection=DBUtil.getConnection();

            String sql="select * from user where userId=?";
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setInt(1,userId);
            //发送
            resultSet=preparedStatement.executeQuery();
            //遍历结果集合 （一条数据，怎么得到各个属性?）
            if(resultSet.next()){
                User user=new User();
                user.setUserId(userId);
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,preparedStatement,resultSet);
        }
        return null;
    }

    public void insertUser(User user) throws SQLException {
        if(user==null){
            return;
        }
        try {
            connection=DBUtil.getConnection();

            String sql="insert into user values(null,?,?)";
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1, user.getUsername());
            preparedStatement.setString(2, user.getPassword());
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,preparedStatement,null);
        }
    }
}
